package com.gitee.sop.layui.adminserver.module.background.admin.view;

import com.gitee.sop.layui.adminserver.module.background.admin.entity.SysMenu;
import com.gitee.sop.layui.adminserver.module.background.admin.service.SysMenuService;
import com.gitee.sop.layui.adminserver.module.base.util.AssertUtil;
import com.gitee.sop.layui.adminserver.module.base.util.ObjectUtil;
import com.gitee.sop.layui.adminserver.module.base.view.BaseViewController;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @author: huwei
 * @date: 2019/11/13 15:05
 * @version: 1.0.0
 */
@Controller
@RequestMapping(value = {"/admin/menu"})
public class SysMenuViewController extends BaseViewController {
    private static final String VIEW_PAGE_PREFIX = "module/admin/sysMenu";

    @Lazy
    @Resource
    private SysMenuService sysMenuService;

    @Override
    protected String prefix() {
        return VIEW_PAGE_PREFIX;
    }


    @Override
    public ModelAndView add(ModelAndView modelAndView, Long id, String key, HttpServletRequest request, HttpServletResponse response) {
        //小功能，显示添加菜单，同级目录的最后排序值
        SysMenu lastMenu = sysMenuService.getOneMaxSortMenuByAppIdAndPid(request.getParameter("appId"), ObjectUtil.isNull(id) ? 0 : id.intValue());
        modelAndView.addObject("nextSort", ObjectUtil.isNull(lastMenu) ? 0 : lastMenu.getSort() + 1);

        modelAndView.addObject("appId", request.getParameter("appId"));
        return super.add(modelAndView, id, key, request, response);
    }

    @Override
    public ModelAndView index(ModelAndView modelAndView, HttpServletRequest request, HttpServletResponse response) {
        modelAndView.addObject("appId", request.getParameter("appId"));
        return super.index(modelAndView, request, response);
    }

    @RequestMapping("/to/tree")
    public ModelAndView toTree(ModelAndView modelAndView) {
        modelAndView.setViewName(prefix().concat("/menuTree.html"));
        return modelAndView;
    }

    @RequestMapping(value = {"/use/template"})
    public ModelAndView permission(ModelAndView modelAndView, String appId) {
        modelAndView.setViewName(prefix().concat("/useMenuTemplate.html"));
        modelAndView.addObject("appId", appId);
        return modelAndView;
    }

    @RequestMapping("/to/append")
    public ModelAndView toAppend(ModelAndView modelAndView, String uri) throws UnsupportedEncodingException {
        AssertUtil.notEmpty(uri, "功能地址不能为空");
        modelAndView.addObject("uri", URLDecoder.decode(uri, "UTF-8"));
        modelAndView.setViewName(prefix().concat("/append.html"));
        return modelAndView;
    }
}
